package com.dony.shop.util;

import cn.hutool.core.net.URLEncodeUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSONObject;
import com.dony.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author sundw
 * @version 1.0.0
 * @description ShopeeUitl
 * @since 2022/8/26 15:38
 */
@Slf4j
@Component
public class TransUtil {

    @Value("${baidu.fayi.appid}")
    private String appid;

    @Value("${baidu.fayi.securityKey}")
    private String securityKey;

    @Value("${baidu.fayi.transHost}")
    private String transHost;

    /**
     * 发送post请求
     *
     * @param content
     * @param from
     * @param to
     * @return
     */
    public String TransPostHandler(String content, String from, String to) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("from", from);
        paramMap.put("to", to);
        paramMap.put("appid", appid);

        // 随机数
        String salt = String.valueOf(System.currentTimeMillis());
        paramMap.put("salt", salt);

        // 签名
        String src = appid + content + salt + securityKey; // 加密前的原文
        paramMap.put("sign", SecureUtil.md5(src));
        paramMap.put("q", URLEncodeUtil.encode(content, StandardCharsets.UTF_8));
        String postResult = HttpUtil.get(transHost, paramMap);
        JSONObject reslut = JSONObject.parseObject(postResult);
        //如果有数据
        if (StringUtils.isEmpty(reslut.getString("error_code"))) {
            List<JSONObject> trans_result = reslut.getList("trans_result", JSONObject.class);
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < trans_result.size(); i++) {
                sb.append("- ").append(trans_result.get(i).getString("dst"));
                if (i<trans_result.size()-1) {
                    sb.append('\n');
                }
            }
            return sb.toString();
        }
        log.error("百度翻译接口调用失败！");
        return null;
    }


    /**
     * 越南文本处理
     *
     * @param content
     * @return
     */
    public String VNTransProcess(String content) {
        content = "- " + content;
        content.replaceAll("\n", "\n- ");
        content.substring(content.length() - 2);
        return content;
    }

}
